package com.weilele.mvvm.base

import android.os.Bundle
import android.view.*
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.*
import com.weilele.mvvm.MvvmConf
import com.weilele.mvvm.base.helper.*
import com.weilele.mvvm.utils.`object`.ScreenAdaptationObj
import com.weilele.mvvm.utils.safeGet
import java.lang.IllegalArgumentException

/**
 * 和dialog一样使用的popupWindow
 * 优先推荐使用dialog，
 * dialog实现有问题的时候可以使用这个尝试
 */
abstract class PopupWindowDialog :
        MvvmPopupWindow(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        ), BaseMvvmInterface, ILifecycleObserver {

    val appCompatActivity: AppCompatActivity
        get() = context.safeGet() ?: throw IllegalArgumentException("使用这个PopupWindow必须需要一个activity")

    /**
     * 创建viewModel
     */
    inline fun <reified T : ViewModel> getActivityViewModel(): T {
        return appCompatActivity.getViewModel()
    }

    /**
     * 这里不需要这个方法
     */
    final override fun getObserverLiveData(): List<LiveDataWrap>? {
        return super.getObserverLiveData()
    }

    /**
     * 获取view
     */
    override fun getLayoutResOrView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): Any? {
        return getLayoutResOrView(inflater, container)
    }

    /**
     * 创建view
     */
    private fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        val contentView = getLayoutResOrView(inflater, container, savedInstanceState)
        val rootView = FrameLayout(inflater.context)
        val contentViewGroup = when (contentView) {
            is Int -> {
                inflater.inflate(contentView, container, false)
            }
            is View -> {
                contentView
            }
            else -> {
                null
            }
        }
        contentViewGroup ?: return null
        rootView.addView(contentViewGroup, rootViewLp)
        return rootView
    }

    private fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        if (view == null) {
            dismiss()
            return
        }
        initUi(savedInstanceState)
        getClickView()?.forEach {
            it?.setOnClickListener(this)
        }
        initData()
    }

    private val rootViewLp by lazy {
        FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.WRAP_CONTENT
        )
    }

    /**
     * 调用之后显示对话框
     */
    open fun show(
            activity: FragmentActivity?,
            gravity: Int = Gravity.CENTER,
            offX: Int = 0,
            offY: Int = 0
    ) {
        activity ?: return
        checkContext(activity)
        //activity.window.decorView 上线文不是activity
        showAtLocation(activity.window.decorView, gravity, offX, offY)
    }

    override fun onPreShow(isAsDropDown: Boolean, gravity: Int) {
        setScreenAdaptation()
        rootViewLp.gravity = gravity
        onRootViewLayoutParams(isAsDropDown, rootViewLp)
        contentView = onCreateView(LayoutInflater.from(appCompatActivity), null, null)
        onViewCreated(contentView, null)
        super.onPreShow(isAsDropDown, rootViewLp.gravity)
    }

    private fun setScreenAdaptation() {
        val act = context
        if (MvvmConf.IS_CAN_SCREEN_ADAPTATION) {
            if (act is MvvmActivity) {
                if (act.isNeedScreenAdaptation()) {
                    ScreenAdaptationObj.setCustomDensity(act.resources)
                }
            } else {
                if (MvvmConf.IS_CAN_SCREEN_OTHER_LIBRARY_ADAPTATION) {
                    ScreenAdaptationObj.setCustomDensity(act?.resources)
                }
            }
        }
    }

    /**
     * 设置布局参数
     */
    protected open fun onRootViewLayoutParams(isAsDropDown: Boolean, lp: FrameLayout.LayoutParams) {
        lp.gravity = Gravity.CENTER
    }


    /**
     * 注册livedata，忽略空的情况
     */
    inline fun <T> observerLiveData(
            bean: LiveData<T>,
            crossinline observer: (T?) -> Unit
    ): Observer<T> {
        return appCompatActivity.observerLiveData(bean, observer)
    }

    /**
     * 注册livedata，只处理成功的情况
     */
    inline fun <T> observerLiveDataSuccess(
            bean: LiveData<StatusValue<T>>,
            crossinline success: (T) -> Unit
    ): Observer<StatusValue<T>> {
        return appCompatActivity.observerLiveDataSuccess(bean, success)
    }
}